package com.wgo.bpot.server.integrationtest.usersession;

import java.io.File;

import com.wgo.bpot.domain.common.AuthenticationHandler;
import com.wgo.bpot.domain.common.MemoryUtil;
import com.wgo.bpot.domain.common.UserCredential;
import com.wgo.bpot.server.service.RemoteServicesImpl;
import com.wgo.bpot.wiring.ServiceAccessor;
import com.wgo.bpot.wiring.WiringEngine;
import com.wgo.precise.client.PreciseHessianRemoteServicesFactory;
import com.wgo.precise.client.common.session.PreciseSession;
import com.wgo.precise.client.common.session.PreciseSessionImpl;
import com.wgo.precise.server.wiring.PreciseServiceAccessor;
import com.wgo.precise.wiring.PreciseWiringImpl;

public class PreciseLocalServicesFactory extends PreciseHessianRemoteServicesFactory {
    private RemoteServicesImpl server;
    private ServiceAccessor serviceAccessor;
    private WiringEngine<PreciseServiceAccessor> wiringEngine = new PreciseWiringImpl();

    public PreciseLocalServicesFactory() {
        this("admin","admin");
    }
    
    public PreciseLocalServicesFactory(final String correctUserName, final String correctPassword) {
        super(null,new AuthenticationHandler(){
            public UserCredential createUserCredential() {
                return new UserCredential(correctUserName,correctPassword);
            }
        });
        System.setProperty(MemoryUtil.PROPERTY_NAME_FOR_LOGGING, Boolean.FALSE.toString());
        System.setProperty(MemoryUtil.PROPERTY_NAME_FOR_ENABLED, Boolean.FALSE.toString());
        System.setProperty(MemoryUtil.PROPERTY_NAME_FOR_GC_ENABLED, Boolean.TRUE.toString());
        String urlStr = UserSessionTest.class.getResource("/precise-integration-test-hibernate.cfg.xml").toExternalForm();
        System.setProperty("hibernatecfg",urlStr);
        server = new RemoteServicesImpl();
        server.init(wiringEngine);
        setRemoteServices(server);
    }

    public void startTransaction(){
        serviceAccessor.getPersistService().startTransaction();
    }
    
    public void commitTransaction(){
        serviceAccessor.getPersistService().commitTransaction();
    }
    
    public PreciseSession createSession(){
        return createSession(false);
    }
    
    public PreciseSession createSession(boolean forceInit){
        PreciseSession session = new PreciseSessionImpl(null,createServices());
        serviceAccessor = server.getServiceAccessor();
        if (forceInit) {
            serviceAccessor.getInitializationService().initialize();
            server.init(wiringEngine);
        } else {
            server.init(wiringEngine);
        }
        return session;
    }
    
    public static File getFile(String fileName){
        File dir = new File(System.getProperty("java.user"),"precise_test");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return new File(dir,fileName);
    }
    
}
